package com.scisoft.scan.control.depotoutsale;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.data.depotoutsale.DOSOrderBean;
import com.scisoft.scan.data.depotoutsale.DOSOrderDetailBean;
import com.scisoft.scan.data.depotoutsale.DOSPartInfoBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_DepotOutSale;
import com.squareup.picasso.Picasso;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class DOSPartQueryActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ClearEditText et_bar;//搜索框
    //零售单
    private DOSOrderBean orderBean;
    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    //分页显示控件
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private DOSPartAdapter docPartAdapter;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在
    float lastY = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_dospart_query);

        //参数传递
        Intent intent = getIntent();
        //销售单
        orderBean = (DOSOrderBean) intent.getSerializableExtra("data");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        });
        et_bar = findViewById(R.id.et_bar);
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true);
            }
        });
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;


        mRefreshLayout = findViewById(R.id.swipe_layout);
        //mRefreshLayout.setEnabled(false);
        mRefreshLayout.setProgressViewEndTarget(true,0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryData(true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        docPartAdapter = new DOSPartAdapter(DOSPartQueryActivity.this);
        docPartAdapter.setItemLayout(R.layout.item_dospart, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        docPartAdapter.setOnItemClickListener(new DOSPartAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                DOSPartInfoBean dosPartInfoBean = docPartAdapter.getItemData(position);
                if("1".equals(dosPartInfoBean.ifGyssm)){
                    //有码件
                    DOSOrderDetailBean docOrderDetailBean = new DOSOrderDetailBean();
                    docOrderDetailBean.partCount = "1";
                    docOrderDetailBean.supplierCode = dosPartInfoBean.manufacturer;
                    docOrderDetailBean.supplierName = dosPartInfoBean.manufacturerName;
                    docOrderDetailBean.partNo = dosPartInfoBean.partNo;
                    docOrderDetailBean.partName = dosPartInfoBean.partName;
                    docOrderDetailBean.ifGyssm = dosPartInfoBean.ifGyssm;
                    docOrderDetailBean.serialNo = dosPartInfoBean.serialNo;
                    CommonUtil.showPress(DOSPartQueryActivity.this);
                    InsertTask insertTask = new InsertTask(DOSPartQueryActivity.this, docOrderDetailBean);
                    insertTask.execute();
                }else{
                    //弹出查询界面
                    alert_edit(dosPartInfoBean);
                }

            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            docPartAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(docPartAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == docPartAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    docPartAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false);
                } else {
                    docPartAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });
        QueryData(true);
    }

    //自定义弹出窗口
    private void alert_edit(final DOSPartInfoBean docPartInfoBean) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_docorderdetail, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        TextView tv_dtlNo = dialogView.findViewById(R.id.tv_dtlNo);
        tv_dtlNo.setText(docPartInfoBean.partNo);
        TextView tv_dtlName = dialogView.findViewById(R.id.tv_dtlName);
        tv_dtlName.setText(docPartInfoBean.partName);
        TextView tv_dtlInfo = dialogView.findViewById(R.id.tv_dtlInfo);
        tv_dtlInfo.setText(docPartInfoBean.manufacturer + " " + docPartInfoBean.manufacturerName);

        final TextView tv_amount = dialogView.findViewById(R.id.tv_amount);
        final TextView et_price = dialogView.findViewById(R.id.et_price);
        final EditText et_count = dialogView.findViewById(R.id.et_count);
        et_price.setText(String.valueOf(docPartInfoBean.price));
        tv_amount.setText(String.valueOf(docPartInfoBean.price));

        et_count.setText("1");
        et_count.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    int count = Integer.parseInt(et_count.getText().toString());
                    double amount = new BigDecimal(count * docPartInfoBean.price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    tv_amount.setText(String.valueOf(amount));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        TextView tv_minus = dialogView.findViewById(R.id.tv_minus);
        tv_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(et_count.getText().toString());
                int temp = count - 1;
                if (temp <= 0) {
                    Toast.makeText(getApplicationContext(), "数量不能小于0", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    et_count.setText(String.valueOf(temp));
                }
            }
        });

        TextView tv_add = dialogView.findViewById(R.id.tv_add);
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(et_count.getText().toString()) + 1;
                et_count.setText(String.valueOf(count));
            }
        });


        TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                DOSOrderDetailBean docOrderDetailBean = new DOSOrderDetailBean();
                docOrderDetailBean.supplierCode = docPartInfoBean.manufacturer;
                docOrderDetailBean.supplierName = docPartInfoBean.manufacturerName;
                docOrderDetailBean.partNo = docPartInfoBean.partNo;
                docOrderDetailBean.partName = docPartInfoBean.partName;
                docOrderDetailBean.ifGyssm = docPartInfoBean.ifGyssm;
                docOrderDetailBean.serialNo = docPartInfoBean.serialNo;
                docOrderDetailBean.partCount = et_count.getText().toString();
                CommonUtil.showPress(DOSPartQueryActivity.this);
                InsertTask insertTask = new InsertTask(DOSPartQueryActivity.this, docOrderDetailBean);
                insertTask.execute();
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //查询库存
    private void QueryData(boolean refresh) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(DOSPartQueryActivity.this, refresh);
        queryTask.execute();
    }

    //绑定数据
    private void BindData(Context context, List<DOSPartInfoBean> newData, boolean refresh) {
        //清空
        docPartAdapter.clearLeftMenuList();
        //数据
        if (!refresh) {
            if (newData.size() > 0) {
                docPartAdapter.addMoreItem(newData);
            } else {
                docPartAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                docPartAdapter.clearAddItem(newData);
            } else {
                docPartAdapter.clearAddItem(newData);
                docPartAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //查询库存服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        private List<DOSPartInfoBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                String condition = et_bar.getUpperText().toString();
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }
                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_DepotOutSale.DEPOT_OUT_SALE_08(condition,orderBean.orderId);
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_DepotOutSale.DEPOT_OUT_SALE_09(condition,orderBean.orderId, pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //增加单个明细服务
    class InsertTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private DOSOrderDetailBean docOrderDetailBean;
        InsertTask(Context context,DOSOrderDetailBean docOrderDetailBean) {
            super();
            mcontext = context;
            this.docOrderDetailBean = docOrderDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {

                msg = WebServiceHelper_DepotOutSale.DEPOT_OUT_SALE_04(orderBean.orderId, docOrderDetailBean);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                //关闭此页面跳转
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //适配器相关功能
    class DOSPartAdapter extends CommonAdapter<DOSPartInfoBean> {
        //构造函数
        public DOSPartAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final DOSPartInfoBean retailPartInfoBean, int position) {
            TextView tv_partNo = holder.getView(R.id.tv_partNo);
            TextView tv_partName = holder.getView(R.id.tv_partName);
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            TextView tv_ycj = holder.getView(R.id.tv_ycj);
            TextView tv_kcs = holder.getView(R.id.tv_kcs);
            TextView tv_kck = holder.getView(R.id.tv_kck);
            TextView tv_ck = holder.getView(R.id.tv_ck);
            TextView tv_hj = holder.getView(R.id.tv_hj);
            TextView tv_price = holder.getView(R.id.tv_price);
            ImageView iv_img = holder.getView(R.id.iv_img);
            //获取相应索引的ItemBean对象
            DOSPartInfoBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_partNo.setText(bean.partNo);
            tv_partName.setText(bean.partName);
            tv_supplierName.setText(bean.manufacturerName);
            String ycj = "1".equals(bean.ifGyssm) ? "有码件" : "无码件";
            tv_ycj.setText(ycj);
            tv_kcs.setText(String.valueOf(bean.stockCount));
            tv_kck.setText(String.valueOf(bean.canUseCount));
            tv_ck.setText(bean.depotName);
            tv_hj.setText(bean.position);
            if (bean.imgUrl != null && !bean.imgUrl.equals("")) {
                Picasso.with(mContext).load(bean.imgUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_noimage));
            }
            tv_price.setText(String.valueOf(bean.price));
        }

    }

}
